<template>
  <el-form
    :model="form"
    ref="form"
    :rules="rules"
    class="form"
  >
    <el-form-item
      class="form-item"
      prop="username"
    >
      <el-input
        placeholder="用户名/手机"
        v-model="form.username"
        @focus="clearRules('username')"
      >
      </el-input>
    </el-form-item>

    <el-form-item
      class="form-item"
      prop="password"
    >
      <el-input
        placeholder="密码"
        type="password"
        v-model="form.password"
        @focus="clearRules('password')"
      >
      </el-input>
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">忘记密码</nuxt-link>
    </p>

    <el-button
      class="submit"
      type="primary"
      @click="handleLoginSubmit"
    >
      登录
    </el-button>
  </el-form>
</template>

<script>
import { login } from "@/api/user";
export default {
  data() {
    return {
      // 表单数据
      form: {
        username: "13800138000",
        password: "123456",
      },
      // 表单规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 6, message: "不能输入少于六位数", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    clearRules(value) {
      this.$refs.form.clearValidate(value);
    },
    // 提交登录
    async handleLoginSubmit() {
      this.$refs.form.validate(async (v) => {
        if (v) {
          let res = await login(this.form);
          if (res && res.data.token) {
            this.$message.success("登录成功");
            this.$store.commit("user/setUserInfo", res.data);
            if (this.$route.name.indexOf("post") != -1) {
              this.$emit("postLogin");
              return;
            }
            this.$router.go(-1);
          }
        } else {
          this.$message.warning("请确认表单是否填写完整");
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.form {
  padding: 25px;
}

.form-item {
  margin-bottom: 20px;
}

.form-text {
  font-size: 12px;
  color: #409eff;
  text-align: right;
  line-height: 1;
}

.submit {
  width: 100%;
  margin-top: 10px;
}
</style>
